package daobeauty.interceptor.invoke.impl;

import java.lang.reflect.Method;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;

import daobeauty.dao.Limiting;
import daobeauty.dao.Sorting;
import daobeauty.interceptor.invoke.AbstractCurrentSessionInvokeStrategy;
import daobeauty.interceptor.invoke.ArgumentMask;
import daobeauty.interceptor.invoke.parser.Parser;
import daobeauty.interceptor.invoke.parser.operator.Operator;
import daobeauty.interceptor.returntype.executor.criteria.CriteriaExecutor;
import daobeauty.util.ArrayListStack;
import daobeauty.util.EmptyStack;
import daobeauty.util.MethodSignatureUtils;
import daobeauty.util.Stack;

public class FindCountByParsingInvoke extends AbstractCurrentSessionInvokeStrategy {
	private static final Log LOG = LogFactory.getLog(FindCountByParsingInvoke.class);
	private final CriteriaExecutor executor;
	private final ArgumentMask argumentMask;
	private final Operator operator; 
	private final ArgumentStackStrategy stackStrategy;
	private final String primaryKeyProperty;
	private final SumStrategy projection;
	
	@SuppressWarnings("unchecked")
	public FindCountByParsingInvoke(Method method, SessionFactory sessionFactory, Class domainClass, Set<String> domainProperties, String primaryKeyProperty) {
		super(sessionFactory, domainClass);
		this.primaryKeyProperty = primaryKeyProperty;
		executor = new CriteriaExecutor(method.getReturnType());
		argumentMask = new ArgumentMask(method, 0);
		if (argumentMask.hasLimiting()){
			throw new IllegalArgumentException("method "+MethodSignatureUtils.toMethodSignature(method)+" may not have a parameter of type "+Limiting.class.getName());
		}
		if (argumentMask.hasSorting()){
			throw new IllegalArgumentException("method "+MethodSignatureUtils.toMethodSignature(method)+" may not have a parameter of type "+Sorting.class.getName());
		}
		String sumType = method.getName().substring(4).toLowerCase();
		if (sumType.startsWith("countdistinct")){
			projection = new DistinctCount();
		}
		else if (sumType.startsWith("count")){
			projection = new Count();
		}
		else{
			throw new IllegalArgumentException("Unknown Sum Type "+sumType);
		}
		final String methodNameWithoutPrefix = method.getName().substring(11); // remove "findCountBy"
		operator = new Parser(methodNameWithoutPrefix, domainProperties, argumentMask.getFilteredParameterTypes()).parse();
		if (argumentMask.getFilteredArgumentsSize()<=0){
			stackStrategy = new EmptyStackStrategy();
		}
		else{
			stackStrategy = new ArrayListStackStrategy();
		}
		if (LOG.isInfoEnabled()){
			LOG.info("created findCountBy strategy with parsing for method "+MethodSignatureUtils.toMethodSignature(method));
			LOG.info("Query with "+operator.getTotalAmountArguments()+" parameters is: "+operator.toTotalString());
		}
		if (operator.getTotalAmountArguments()!=argumentMask.getFilteredArgumentsSize()){
			LOG.warn("Amount of needed parameters for query ("+operator.getTotalAmountArguments()+") and defined parameters in method ("+argumentMask.getFilteredArgumentsSize()+") don't match.");	
		}
	}
	
	@SuppressWarnings("unchecked")
	public Object invoke(String methodName, Object[] args) throws Exception {
		final Criteria criteria = createCriteria();
		criteria.add(operator.createCriterion(stackStrategy.getArgumentStack(argumentMask.getFiltered(args))));
		criteria.setProjection(projection.createProjection());
		return executor.execute(criteria, null, null);
	}
	
	private interface SumStrategy{
		public Projection createProjection();
	}
	
	private class Count implements SumStrategy{
		public Projection createProjection() {
			return Projections.count(primaryKeyProperty);
		}
	}

	private class DistinctCount implements SumStrategy{
		public Projection createProjection() {
			return Projections.countDistinct(primaryKeyProperty);
		}
	}

	
	private interface ArgumentStackStrategy{
		public Stack getArgumentStack(Object [] arguments);
	}
	
	private static class EmptyStackStrategy implements ArgumentStackStrategy{
		public Stack getArgumentStack(Object[] arguments) {
			return EmptyStack.INSTANCE;
		}
	}

	private static class ArrayListStackStrategy implements ArgumentStackStrategy{
		@SuppressWarnings("unchecked")
		public Stack getArgumentStack(Object[] arguments) {
			final ArrayListStack stack = new ArrayListStack(arguments.length);
			for (int i=arguments.length-1; i>=0; i--){
				stack.push(arguments[i]);
			}
			return stack;
		}
	}

}
